package initialize

import (
	"log"
	"runtime"

	"github.com/bwmarrin/snowflake"
	conf "longblog/framework/tools/conf"
	kgorm "longblog/framework/tools/db/gorm"
	kredis "longblog/framework/tools/db/redis"
	klog "longblog/framework/tools/log"
	kruntime "longblog/framework/tools/runtime"
	"github.com/jinzhu/gorm"
)

const CONFIG_PATH = "conf/config.ini"

var Conf *conf.Kconf

var LogError *klog.LlogFile
var LogWarn *klog.LlogFile
var LogInfo *klog.LlogFile
var LogDebug *klog.LlogFile

var Gorm *gorm.DB
var RedisPool *kredis.RedisPool
var SnowflakeNode *snowflake.Node

func init() {
	var err error
	runtime.GOMAXPROCS(runtime.NumCPU()) //多核设置

	///--------------
	Conf, err = conf.NewKconf(CONFIG_PATH)
	if err != nil {
		log.Panic("conf parse fail:", err)
	}

	///--------------
	LogError = klog.Error
	LogWarn = klog.Warn
	LogInfo = klog.Info
	LogDebug = klog.Debug

	///--------------
	SnowflakeNode, err = snowflake.NewNode(10)
	if err != nil {
		log.Println(err)
	}

}

func InitConf(confile string) {
	conft, err := conf.NewKconf(confile)
	if err != nil {
		log.Panic("conf parse fail:", err)
	}
	Conf = conft
}

func InitLog(logfile string) {
	kruntime.CreateDir("log")
	LogError, _ = klog.NewLlogFile("log/"+logfile+"_err.log", "[Error]", klog.LstdFlags|klog.Lshortfile, klog.LOG_LEVEL_ERROR, klog.LOG_LEVEL_ERROR, 50)
	// LogWarn, _ = klog.NewLlogFile("log/"+logfile+"_warn.log", "[Warn]", klog.LstdFlags|klog.Lshortfile, klog.LOG_LEVEL_ERROR, klog.LOG_LEVEL_ERROR, 50)
	// LogInfo, _ = klog.NewLlogFile("log/"+logfile+"_info.log", "[Info]", klog.LstdFlags|klog.Lshortfile, klog.LOG_LEVEL_ERROR, klog.LOG_LEVEL_ERROR, 50)
	// LogDebug, _ = klog.NewLlogFile("log/"+logfile+"_debug.log", "[Debug]", klog.LstdFlags|klog.Lshortfile, klog.LOG_LEVEL_ERROR, klog.LOG_LEVEL_ERROR, 50)

	LogWarn = LogError
	LogInfo = LogError
	LogDebug = LogError
}

func InitMysql() {
	mysql_user, _ := Conf.GetString("mysql", "user")
	mysql_password, _ := Conf.GetString("mysql", "password")
	mysql_ip, _ := Conf.GetString("mysql", "ip")
	mysql_port, _ := Conf.GetString("mysql", "port")
	mysql_mysqldb, _ := Conf.GetString("mysql", "mysqldb")
	tmpGorm, err := kgorm.NewGorm(mysql_user, mysql_password, mysql_ip, mysql_port, mysql_mysqldb)
	if err != nil {
		log.Panic(err)
	}
	Gorm = tmpGorm
}
func InitRedis() {
	redis_host, _ := Conf.GetString("redis", "host")
	redis_port, _ := Conf.GetString("redis", "port")
	redis_auth, _ := Conf.GetString("redis", "auth")
	tmpRedisPool, err := kredis.NewRedisPool(redis_host, redis_port, redis_auth)
	if err != nil {
		log.Panic(err)
	}
	RedisPool = tmpRedisPool
}
